<script setup>
import { ref, reactive, onMounted } from "vue";
import {RegisterDevice} from "../../wailsjs/go/api/DeviceApi.js"
import {GetImage} from "../../wailsjs/go/api/FileSystem.js";
import {
  GetCustomerInfoById,
} from "../../wailsjs/go/api/CustomerApi.js";
import { SaveToken, GetUserOrganList } from "../../wailsjs/go/api/AuthApi.js";
import {
  CheckCameraAvailability,StopCameraCaptureForClient,
  FaceMeasurement,CameraCapture
} from "../../wailsjs/go/api/CameraApi.js";
import {
  ListTreeChecklistInfos,
  QueryChecklistInfoById,
} from "../../wailsjs/go/api/ReportApi.js";

const data = reactive({
  name: "",
  resultText: "Please enter your name below 👇",
});

function greet() {}
const listCustomers = async () => {
  // const result = await GetTreeCustomerList({page:1,pageSize:10})
  const result = await GetCustomerInfoById(937);
  console.log(result);
};

async function saveToken() {
  const token1 = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjM2NDQsInVzZXJOYW1lIjoiMTMyMTExMTAwMDIiLCJ1bmlxdWVOdW1iZXIiOiIwYWQzMDQ3MC02ODNiLTQxZWMtYWMyYy0zN2VjZmNlZjkyMTAiLCJ1c2VyQXR0ciI6Intkb209NFx1MDAyNlx1MDAyNjE9M1x1MDAyNlx1MDAyNjI9Nn0iLCJwaG9uZSI6IjEzMjExMTEwMDAyIiwidXNlck5pY2tOYW1lIjoi6ZuE5Y2a5biC5Zy66YOo6KeG5YWJ5Lit5b-DIiwib3JnYW5pemF0aW9uSWQiOjIyMTAxOCwiZG9tVmFsdWUiOiJzdG9yZWJtcyIsIm9yZ2FuQ2xhc3NpZmljYXRpb25JZCI6MywiZGVwQW5kUG9zIjpbeyJkZXBhcnRtZW50SWQiOjExNiwicG9zaXRpb25JZCI6NzR9XSwiQnVmZmVyVGltZSI6ODY0MDAsImlzcyI6Inl0eGIiLCJhdWQiOlsiWVRYQiJdLCJleHAiOjE3NTYyNTkwNzcsIm5iZiI6MTc1NTY1MzI3N30.GXIV_VETIv3pq4E4PLjc3werOOZM5vfGVURg8cF-s3Q";
  await SaveToken(token1);
  console.log("save token success");
}

onMounted(async () => {
  // await listCustomers();
});

async function listChecklistInfos() {
  const result = await ListTreeChecklistInfos({ page: 1, size: 10 });
  console.log(result);
}
async function queryChecklistInfoById() {
  const result = await QueryChecklistInfoById(2173);
  console.log(result);
}
async function getOrganizeList() {
  const result = await GetUserOrganList("18088888888");
  console.log(result);
}
const cameraData1 = ref([]);
const cameraData2 = ref([]);
const ws1 = ref(null);
const ws2 = ref(null);
const cid1 = ref("");
const cid2 = ref("");

const startCamera = async (id) => {
  // 调用后端方法启动摄像头
  if (id === 1) {
    // if (cid1.value !== "") {
    //   console.log("camera is already started");
    //   return;
    // }
    // console.log("start camera 1")
    // 接受画面
    ws1.value = new WebSocket('ws://localhost:8090/ws')
    ws1.value.onmessage = handleMessage // 接收消息
    // ws1.value.onerror = handleOnError
  } else if (id === 2) {
    if (cid2.value !== "") {
      console.log("camera is already started");
      return;
    }
    ws2.value = new WebSocket("ws://localhost:8090/ws");
    ws2.value.onmessage = handleMessage2; // 接收消息
    // ws2.value.onerror = handleOnError
  }
};
const cameraImg1 = ref("");
const cameraImg2 = ref("");
const videoCanvas = ref(null);
const ctx = ref(null)
const initCanvas = () => {
  const canvas = videoCanvas.value
  canvas.width = canvas.clientWidth
  canvas.height = canvas.clientHeight
  ctx.value = canvas.getContext('2d', { willReadFrequently: false })
}
const handleMessage = (event) => {
  console.log("websocket receive data", event.data);
  if (typeof event.data === "string") {
    const header = JSON.parse(event.data);
    if (header.type === "ping") {
      cid1.value = header.cid;
      console.log("cid is", header.cid);
    } else if (header.type === "data") {
      ws1.value.binaryType = "arraybuffer"; //下一个消息是二进制视频数据
    }
  } else if (event.data instanceof ArrayBuffer) {
    // 将ArrayBuffer转为Blob
    const blob = new Blob([event.data], { type: "image/jpeg" });
    // 2. 创建对象URL
    const imageUrl = URL.createObjectURL(blob);
    renderFrame(imageUrl);
    setTimeout(() => {
      URL.revokeObjectURL(imageUrl);
    }, 100);
  }
};

// 渲染到Canvas
const renderFrame = (imageData) =>{
  const img = new Image()
  img.onload = () => {
    const canvas = videoCanvas.value
    const ratio = Math.min(
        canvas.width / img.width,
        canvas.height / img.height
    )
    const drawWidth = img.width * ratio
    const drawHeight = img.height * ratio
    ctx.value.clearRect(0, 0, canvas.width, canvas.height)
    ctx.value.drawImage(
        img,
        (canvas.width - drawWidth) / 2,
        (canvas.height - drawHeight) / 2,
        drawWidth,
        drawHeight
    )
  }
  img.src = imageData
}

const handleMessage2 = (event) => {
  const value = JSON.parse(event.data);
  if (value.type === "ping") {
    cid2.value = value.cid;
    console.log("cid is", value.cid);
  } else if (value.type === "data") {
    cameraImg2.value = value.data;
  }
};

const stopCamera = async (id) => {
  // 调用后端方法停止摄像头
  if (id === 1) {
    if (cid1.value === "") return;
    await StopCameraCaptureForClient(cid1.value); //停止摄像头
    if (ws1.value && ws1.value.readyState === WebSocket.OPEN) {
      ws1.value.close();
    }
    cid1.value = "";
    ws1.value = null;
  } else if (id === 2) {
    if (cid2.value === "") return;
    await StopCameraCaptureForClient(cid2.value); //停止摄像头
    if (ws2.value && ws2.value.readyState === WebSocket.OPEN) {
      ws2.value.close();
    }
    cid2.value = "";
    ws2.value = null;
  }
};

// concurrent write to websocket connection
onMounted(async () => {
  initCanvas()
  const cameraAva = await CheckCameraAvailability(0)
  // if(cameraAva.code === 0) {
  //     await startCamera(1)
  // }
})

const capturePicture = async () => {
  const { code, path } = await CameraCapture();
  if (code === -1) {
    console.log("未识别到正中心人脸");
    return;
  }
  const imageData = await GetImage(path);
  capturingPath.value = path
  console.log("path",path)
  capturing.value = `data:image/jpeg;base64,${imageData}`;
}
const capturing = ref("")
const capturingPath = ref("")

// 坐标还原
// 右眼尺寸: 7.66mm (宽) x 1.59mm (高)
// 左眼尺寸: 7.02mm (宽) x 1.59mm (高)
// 内眼角距离：12.76mm, 外眼角距离：27.43mm
// 颞部宽度：42.84mm, 下颌宽度：41.27mm, 下颚宽度34.89mm
// 右内眦角度：27.68°， 左内眦角度：34.59°, 右外眦角度37.23°, 左外眦角度45.00°
// 脸部黄金三角角度74.97°
// 瞳距20.44mm
const faceMeasurement = async () => {
  const result = await FaceMeasurement(capturingPath.value)
  console.log("faceMeasurement",result)
}
const registerDevice = async () => {
  //	 outCode: string;
  // categoryId: number;
  // categoryName: string;
  // typeId: number;
  // typeName: string;
  // brandName: string;
  // brandId: number;
  // deviceName: string;
  const result = await RegisterDevice({
    outCode: "123456",
    categoryId: 1,
    categoryName: "测试",
    deviceName: "测试",
    typeId: 1,
    typeName: "测试",
    brandName: "测试",
    brandId: 1,
  })
  console.log("registerDevice",result)
}

</script>
<template>
  <main>
    <div style="display: flex" class="hello">
        <div class="left-camera" style="display: flex;flex-direction: column;align-items: center;">
          <div>
            camera1:
          </div>
          <div class="content">
<!--            <div v-for="item in cameraData1" >-->
<!--              <img id="image" alt="Base64 Image" width="300" height="300"/>-->
<!--            </div>-->
<!--            <img  :src="cameraImg1" alt="" >-->
            <canvas ref="videoCanvas"></canvas>
          </div>
          <div style="display: flex;justify-content: center;margin-top: 10px;">
            <button @click="startCamera(1)">startCamera</button>
            <button @click="stopCamera(1)">stopCamera</button>
            <button @click="capturePicture">capturePicture</button>
<!--            <button @click="faceMeasurement">faceMeasurement</button>-->
          </div>
        </div>
      <div v-if="capturing">
        <div>
          picture:
        </div>
        <img :src="capturing" alt="" >
        <button @click="faceMeasurement">faceMeasurement</button>
      </div>
      <div>
        <button @click="registerDevice">registerDevice</button>
        <button @click="saveToken">saveToken</button>
      </div>
      <!--      <div class="left-camera" style="display: flex;flex-direction: column;align-items: center;">-->
<!--        <div>-->
<!--          camera2:-->
<!--        </div>-->
<!--        <div class="content">-->
<!--          &lt;!&ndash;            <div v-for="item in cameraData1" >&ndash;&gt;-->
<!--          &lt;!&ndash;              <img id="image" alt="Base64 Image" width="300" height="300"/>&ndash;&gt;-->
<!--          &lt;!&ndash;            </div>&ndash;&gt;-->
<!--          <img  :src="cameraImg2" alt="" >-->
<!--        </div>-->
<!--        <div style="display: flex;justify-content: center;margin-top: 10px;">-->
<!--          <button @click="startCamera(2)">startCamera</button>-->
<!--          <button @click="stopCamera(2)">stopCamera</button>-->
<!--        </div>-->
<!--      </div>-->
    </div>
  </main>
</template>

<style scoped lang="scss">
.hello {
  button {
    border: 2px solid #c4c4c4;
    margin-right: 20px;
  }
}
.left-camera {
  .content {
    margin-bottom: 10px;
    min-height: 400px;
    width: 100%;
    border: 1px solid black;
    position: relative;
    aspect-ratio: 16/9; /* 保持固定宽高比 */
    canvas {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%!important;
      height: 100%!important;
    }
  }
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
